package fr.azzale.casu.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.util.Xml;
import fr.azzale.casu.TribuneApplication;
import fr.azzale.casu.metier.Casu;
import fr.azzale.casu.metier.Line;
import fr.azzale.casu.metier.Tribune;

public class Utils {

	public static final String PROFILE_URL = "http://www.casugaming.com/index.php?action=profile;u=";
	public static final String URLINDEX = "http://www.casugaming.com/index.php";
	public static final String URLLOGIN2 = "http://www.casugaming.com/index.php?action=login2";
	private static final String HTTP_POST_MSG = "http://www.casugaming.com/index.php?action=shoutbox;sa=send;sesc=#;xml;row=";
	public static String URLGET = "http://www.casugaming.com/index.php?action=shoutbox;sa=get;xml;row=0;restart";
	public static String URLLOGIN = "http://www.casugaming.com/index.php?action=login";
	   
	public static String readAuthPage(Context ctx)
	{
		try {
	        Resources res = ctx.getResources();
	        InputStream in_s = new URL(URLLOGIN).openStream();//res.openRawResource(R.raw.login);

	        byte[] b = new byte[in_s.available()];
	        in_s.read(b);
	       return new String(b);
	    } catch (Exception e) {
	    }
	    return null;
	}
	public static void serializeObject(Activity ctx, Object o, String filename) { 
	    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
	 
	    try { 
	      ObjectOutput out = new ObjectOutputStream(ctx.openFileOutput(filename, Context.MODE_PRIVATE)); 
	      out.writeObject(o); 
	      out.close(); 
	    } catch(IOException ioe) { 
	      Log.e("serializeObject", "error", ioe); 
	    } 
	  } 
	public static Object deserializeObject(Activity ctx, String filename) { 
	    try { 
	      ObjectInputStream in = new ObjectInputStream(ctx.openFileInput(filename)); 
	      Object object = in.readObject(); 
	      in.close(); 
	 
	      return object; 
	    } catch(ClassNotFoundException cnfe) { 
	      Log.e("deserializeObject", "class not found error", cnfe); 
	 
	      return null; 
	    } catch(IOException ioe) { 
	      Log.e("deserializeObject", "io error", ioe); 
	 
	      return null; 
	    } 
	  } 
	private static DefaultHttpClient httpclient = new DefaultHttpClient();
	public static Tribune getTribuneFromWeb(Context ctx, String unparsedCookie) {
		SAXParserFactory fabrique = SAXParserFactory.newInstance();
		SAXParser parseur = null;
		ArrayList<Line> entries = null;

		try {
			parseur = fabrique.newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		DefaultHandler handler = new ParserXMLHandler(ctx);

		try {
			BasicCookieStore cookieStore = new BasicCookieStore();
			String login_cookie_string = unparsedCookie;
			String[] cookies = null;
			String[] cookie_parts = null;
			if(login_cookie_string!=null && login_cookie_string.length()> 0)
			{
				cookies = login_cookie_string.split(";");
				for(String cookie: cookies)
				{	
					cookie_parts = cookie.split("=");
					if(cookie_parts.length == 2)
					{
						for(int t=0;t< cookie_parts.length;t++)
						{
							//debug_view.append("part "+cookie_parts[t]);
						}
						Cookie login_cookie = new BasicClientCookie(cookie_parts[0].trim(),cookie_parts[1]);
						((BasicClientCookie) login_cookie).setDomain("www.casugaming.com");
						cookieStore.addCookie(login_cookie);
					}
					else
					{
						//debug_view.setText(" couldnt split cookies ");
					}
				}
			}
			else
			{
				//debug_view.setText(" no cookie ");
			}
			httpclient.setCookieStore(cookieStore);
			
			HttpGet request = new HttpGet(URLGET);
			int status = 0;
			try
			{
				HttpResponse http_response = httpclient.execute(request);
				status = http_response.getStatusLine().getStatusCode();
				if (status != HttpStatus.SC_OK)
				{
					Log.d("getLine","NOK");
				}
				else
				{
					InputStream content = http_response.getEntity().getContent();
					if (content == null)
						Log.e("erreur android", "null");
					else {
						BufferedReader br = new BufferedReader(new InputStreamReader(content));
						FileOutputStream fos = ctx.openFileOutput("tribune.xml", Context.MODE_PRIVATE);
						String line = "";
						String transformedContent ="";
						fos.write("<tribune>".getBytes());
						while((line= br.readLine())!=null)
						{
							if(line.startsWith("	<msgs><![CDATA["))
							{
								transformedContent = line.substring("	<msgs><![CDATA[".length(), line.indexOf("<tr id=\"shoutbox_msgs\">"))
																	.replaceAll("</div>", "</span>")
																	.replaceAll("><", ">\n<")
																	.replaceAll("> <", ">\n<");
//								Log.d("saveXML", "found tribune:" +transformedContent);
								fos.write(transformedContent.getBytes());
							}
						}
						fos.write("</tribune>".getBytes());
						fos.flush();
						fos.close();
						FileInputStream fis = ctx.openFileInput("tribune.xml"); 
						
						parseur.parse(fis, handler);
						entries = ((ParserXMLHandler) handler).getData();
					}
				}
			}
			catch (ClientProtocolException e)
			{
				Log.d("getLine",""+e.getMessage());
			}
			catch (IOException e)
			{
				Log.d("getLine",""+e.getMessage());
			}
		} catch (SAXException e) {
			e.printStackTrace();
		}
		Tribune t = new Tribune();
		t.setData(entries);
		return t;

	}

	public static String postMessage(Activity tribuneActivity, String message, String sessionID, String row) {
		String url = HTTP_POST_MSG.replace("#", sessionID)+row;//+"&msg="+message;
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 		 
		nameValuePairs.add(new BasicNameValuePair("msg", message));
		try {
			HttpResponse response = httpclient.execute(httppost);
			response.getStatusLine().getStatusCode();
			
			InputStream is = response.getEntity().getContent();
			byte[] buffer = new byte[1024];
			while(is.read(buffer)>-1)
			{
				Log.d("return", ""+new String(buffer));
			}
		} catch (ClientProtocolException e) {
			return e.getMessage();
		} catch (IOException e) {
			return e.getMessage();
		}
		return null;
	}

	public static String getSessionID(Activity ctx) {
		return ctx.getSharedPreferences("Casu", Context.MODE_PRIVATE).getString("sessionid", "");
	}
	private static final Pattern HTML_A_TAG_PATTERN = Pattern.compile(".*(?i)<a([^>]+)>(.+?)</a>");

private static final Pattern HTML_A_HREF_TAG_PATTERN = Pattern.compile("\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))");
	public static String[] extractURLs(String line) {
		Matcher matcherTag = HTML_A_TAG_PATTERN.matcher(line);

		ArrayList<String> result = new ArrayList<String>();
		while(matcherTag.find()){			 
			  String href = matcherTag.group(1); //href
			  String linkText = matcherTag.group(2); //link text
			  Matcher matcherLink = HTML_A_HREF_TAG_PATTERN.matcher(href);
			  while(matcherLink.find()){
				  String link = matcherLink.group(1); //link
				  result.add(link);
			  }
		  }
		String[] urls = new String[result.size()];
		for(int i =0; i<result.size();i++)
			urls[i] = result.get(i);
		return urls;
	}

	public static int getMonth(String time) {
		if(time==null)
			return -1;
		if(time.equals("Jan"))
			return Calendar.JANUARY;
		if(time.equals("Feb"))
			return Calendar.FEBRUARY;
		if(time.equals("Mar"))
			return Calendar.MARCH;
		if(time.equals("Apr"))
			return Calendar.APRIL;
		if(time.equals("May"))
			return Calendar.MAY;
		if(time.equals("Jun"))
			return Calendar.JUNE;
		if(time.equals("Jul"))
			return Calendar.JULY;
		if(time.equals("Aug"))
			return Calendar.AUGUST;
		if(time.equals("Sep"))
			return Calendar.SEPTEMBER;
		if(time.equals("Oct"))
			return Calendar.OCTOBER;
		if(time.equals("Nov"))
			return Calendar.NOVEMBER;
		if(time.equals("Dec"))
			return Calendar.DECEMBER;
		
		
		return -1;
	}
}
